package com.bailian.web.controller.system;

import com.bailian.common.annotation.Log;
import com.bailian.common.core.controller.BaseController;
import com.bailian.common.core.domain.AjaxResult;
import com.bailian.common.enums.BusinessType;
import com.bailian.framework.web.service.JwtTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT演示控制器
 * 展示统一的JWT token生成和管理功能
 * 
 * @author bailian
 */
@RestController
@RequestMapping("/jwt/demo")
public class JwtDemoController extends BaseController {

    @Autowired
    private JwtTokenService jwtTokenService;

    /**
     * 生成标准JWT token
     */
    @PostMapping("/generate/standard")
    @Log(title = "生成标准JWT token", businessType = BusinessType.OTHER)
    public AjaxResult generateStandardToken(@RequestBody Map<String, Object> params) {
        try {
            // 模拟用户信息
            Long userId = Long.valueOf(params.get("userId").toString());
            String username = params.get("username").toString();
            String permissions = params.get("permissions").toString();
            
            String token = jwtTokenService.generateApiToken(userId, username, permissions);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenType", "STANDARD");
            result.put("userId", userId);
            result.put("username", username);
            
            return AjaxResult.success("生成标准JWT token成功", result);
        } catch (Exception e) {
            return AjaxResult.error("生成JWT token失败: " + e.getMessage());
        }
    }

    /**
     * 生成管理员JWT token
     */
    @PostMapping("/generate/admin")
    @Log(title = "生成管理员JWT token", businessType = BusinessType.OTHER)
    public AjaxResult generateAdminToken(@RequestBody Map<String, Object> params) {
        try {
            // 模拟管理员用户信息
            Long userId = Long.valueOf(params.get("userId").toString());
            String username = params.get("username").toString();
            String permissions = params.get("permissions").toString();
            String roles = params.get("roles").toString();
            
            // 这里需要创建LoginUser对象，简化处理
            // 注意：实际使用时应该通过真实的LoginUser对象来生成token
            String token = jwtTokenService.generateApiToken(userId, username, permissions);
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenType", "ADMIN");
            result.put("userId", userId);
            result.put("username", username);
            result.put("roles", roles);
            result.put("note", "这是模拟token，实际使用时请通过LoginUser对象生成");
            
            return AjaxResult.success("生成管理员JWT token成功", result);
        } catch (Exception e) {
            return AjaxResult.error("生成管理员JWT token失败: " + e.getMessage());
        }
    }

    /**
     * 验证JWT token
     */
    @PostMapping("/validate")
    @Log(title = "验证JWT token", businessType = BusinessType.OTHER)
    public AjaxResult validateToken(@RequestBody Map<String, Object> params) {
        try {
            String token = params.get("token").toString();
            
            boolean isValid = jwtTokenService.validateToken(token);
            boolean isExpired = jwtTokenService.isTokenExpired(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("valid", isValid);
            result.put("expired", isExpired);
            
            if (isValid && !isExpired) {
                Long userId = jwtTokenService.getUserIdFromToken(token);
                String username = jwtTokenService.getUsernameFromToken(token);
                String authorities = jwtTokenService.getAuthoritiesFromToken(token);
                
                result.put("userId", userId);
                result.put("username", username);
                result.put("authorities", authorities);
            }
            
            return AjaxResult.success("JWT token验证完成", result);
        } catch (Exception e) {
            return AjaxResult.error("JWT token验证失败: " + e.getMessage());
        }
    }

    /**
     * 刷新JWT token
     */
    @PostMapping("/refresh")
    @Log(title = "刷新JWT token", businessType = BusinessType.OTHER)
    public AjaxResult refreshToken(@RequestBody Map<String, Object> params) {
        try {
            String token = params.get("token").toString();
            
            String newToken = jwtTokenService.refreshToken(token);
            
            Map<String, Object> result = new HashMap<>();
            result.put("oldToken", token);
            result.put("newToken", newToken);
            result.put("message", "JWT token刷新成功");
            
            return AjaxResult.success("JWT token刷新成功", result);
        } catch (Exception e) {
            return AjaxResult.error("JWT token刷新失败: " + e.getMessage());
        }
    }

    /**
     * 获取JWT配置信息
     */
    @GetMapping("/config")
    public AjaxResult getJwtConfig() {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("message", "JWT统一配置已启用");
            config.put("features", new String[]{
                "统一JWT token生成",
                "多种token类型支持",
                "自动token验证",
                "token刷新机制",
                "配置化管理"
            });
            
            return AjaxResult.success("获取JWT配置信息成功", config);
        } catch (Exception e) {
            return AjaxResult.error("获取JWT配置信息失败: " + e.getMessage());
        }
    }
} 